package core

import (
	"fmt"
	"sync"
	"time"
)

type LogCall func(log string)
type Log struct {
	logcall LogCall
	logChan chan string
}

var (
	instance_log *Log
	once_log     sync.Once
)

func GetLog() *Log {
	once_log.Do(func() {
		// 数据总线，用于应用间通信
		instance_log = &Log{logcall: nil, logChan: make(chan string, 100)}
	})
	return instance_log
}

func (l *Log) OnEvent(call LogCall) *Log {
	l.logcall = call
	return l
}
func (l *Log) Run() {
	go func() {
		for {
			buf := <-l.logChan
			if l.logcall != nil {
				l.logcall(buf)
			}
		}
	}()
}

func (l *Log) ShowLog(a ...any) {
	buf := fmt.Sprintln("["+time.Now().Format(time.DateTime)+"]", a)
	l.logChan <- buf
}
